package com.wbase.permission.helper

import androidx.fragment.app.Fragment
import com.wbase.permission.request.Permission
import com.wbase.permission.request.PermissionRequester
import java.util.concurrent.Executors

object FragmentPermissionHelper: AbsPermissionHelper() {
    private const val TAG = "FragmentPermissionHelper"

    fun checkPermissionList(fragment: Fragment,
                            requestList: ArrayList<String>,
                            body: (deniedList: ArrayList<String>,
                                   isAll: Boolean) -> Unit = {list:ArrayList<String>,isAll: Boolean->}) {

        Executors.newSingleThreadExecutor().execute {
            val deniedList = ArrayList<String>()
            var isAllPermission = true
            if (isSdkUp23()) {
                requestList.forEach {
                    if(!hasPermission(it)){
                        isAllPermission = false
                        deniedList.add(it)
                    }
                }
            }

            fragment.activity?.runOnUiThread {
                body(deniedList,isAllPermission)
            }
        }
    }



    /**
     * 权限请求
     * @param body 第一个参数:true-用户点击了不在询问并拒,第3个参数:true-全部允许, false-有权限拒绝
     */
    fun requestPermissionList(fragment: Fragment, requestList: ArrayList<String>,
                              callback: (isAllGranted: Boolean,
                                     isAllCantShow: Boolean,
                                     deniedList: ArrayList<String>,
                                     list: ArrayList<Permission>) -> Unit) {
        if (isSdkUp23()) {
            PermissionRequester(fragment).requestPermissions(requestList,callback)
        } else {
            onAllPermissionGranted(requestList, callback)
        }
    }

    fun checkAndRequestPermissionList(fragment: Fragment,
                                      requestList: ArrayList<String>,
                                      callback: (isAllGranted: Boolean,
                                                 isAllCantShow: Boolean,
                                                 deniedList: ArrayList<String>,
                                                 list: ArrayList<Permission>) -> Unit){

        checkPermissionList(fragment, requestList) { deniedList, isAll ->
            if (!isAll) {
                requestPermissionList(fragment, deniedList, callback)
            } else {
                onAllPermissionGranted(requestList, callback)
            }
        }
    }

    override fun getTag(): String {
        return TAG
    }
}